import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
import javax.swing.JOptionPane;
import JavaBean.User;
/**
 * @author Sai
 * Created by Sai on 2019-03-03.
 */
@WebServlet(urlPatterns = {"/LOGIN"})
public class LOGIN extends HttpServlet {

    @Override

    protected void service(HttpServletRequest request, HttpServletResponse response) throws  IOException {
        int flag=0;
        String name= request.getParameter("username");
        String password=request.getParameter("password1");
        String PersonalMessage;
        try {
            String root = System.getProperty("user.dir");
            String FileName="Usermessage.txt";
            String filepath = root+File.separator+FileName;
            FileReader fd1 = new FileReader(filepath);
            BufferedReader reader = new BufferedReader(fd1);
            while((PersonalMessage = reader.readLine()) != null){
                String message[] = PersonalMessage.split(" ");
                if (message[0].equals(name) && message[2].equals(password)){
                    flag=1;
                    HttpSession session = request.getSession();
                    User user = new User(message[0],message[1],message[2],message[3],message[4]);
                    session.setAttribute("user",user);
                }
            }
            fd1.close();
            reader.close();
        }
        catch(IOException e){
            response.sendRedirect("/error.jsp");
        }
        if(flag==0){
            JOptionPane.showMessageDialog(null, "账号密码错误", "请重新登录", JOptionPane.ERROR_MESSAGE);
            response.sendRedirect("/Loging.jsp");
        }
        else
            response.sendRedirect("/UserPage.jsp");
    }
}
